/*
 * @Author: Await
 * @Date: 2025-04-18 09:55:45
 * @LastEditors: Await
 * @LastEditTime: 2025-04-22 17:00:47
 * @Description: 图例配置组件
 */

import React, { useState, useCallback } from 'react';
import {
    Form,
    Switch,
    Input,
    Select,
    Divider,
    Row,
    Col,
    Typography,
    InputNumber,
    Space,
    Tabs,
    Collapse,
    Button,
    Tooltip,
    Popover,
    Modal,
    message
} from 'antd';
import { LegendConfig as LegendConfigType } from '../../../types/index';
import ColorPicker from '../../Common/ColorPicker';
import {
    QuestionCircleOutlined,
    LinkOutlined,
    SaveOutlined,
    DeleteOutlined,
    ImportOutlined,
    ExportOutlined
} from '@ant-design/icons';
import type { TabsProps, CollapseProps } from 'antd';
import { useLocalStorage } from '../../../hooks/useLocalStorage';
import { useLegendPresets } from '../../../hooks/useLegendPresets';

// 默认值配置
const DEFAULT_VALUES = {
    padding: 5,
    itemWidth: 25,
    itemHeight: 14,
    itemGap: 10,
    borderWidth: 0,
    borderRadius: 0,
    shadowBlur: 0,
    shadowOffsetX: 0,
    shadowOffsetY: 0,
    pageIconSize: 15,
    animationDurationUpdate: 800
};

interface LegendConfigProps {
    legend: LegendConfigType;
    onChange: (legend: LegendConfigType) => void;
}

/**
 * 图例配置组件
 */
const LegendConfig: React.FC<LegendConfigProps> = ({
    legend,
    onChange
}) => {
    const [activeTab, setActiveTab] = useState('1');
    const [showPresetModal, setShowPresetModal] = useState(false);
    const [presetName, setPresetName] = useState('');
    const [lastAppliedPreset, setLastAppliedPreset] = useLocalStorage<string>('last-applied-legend-preset', '');

    // 使用图例预设钩子
    const { allPresets, saveAsPreset, deletePreset } = useLegendPresets();

    // 应用预设
    const applyPreset = useCallback((presetConfig: LegendConfigType) => {
        onChange(presetConfig);
    }, [onChange]);

    // 保存当前配置为预设
    const handleSavePreset = useCallback(() => {
        if (!presetName.trim()) {
            message.error('请输入预设名称');
            return;
        }

        if (saveAsPreset(presetName, legend)) {
            setShowPresetModal(false);
            setPresetName('');
            setLastAppliedPreset(presetName);
        }
    }, [presetName, legend, saveAsPreset, setLastAppliedPreset]);

    // 处理数值类型的公共函数
    const handleNumberValue = (value: number | null | undefined, defaultValue: number): number => {
        if (value === null || value === undefined) {
            return defaultValue;
        }
        return value;
    };

    const handleChange = (key: keyof LegendConfigType, value: any) => {
        // 数值类型的属性处理
        if (key in DEFAULT_VALUES && (typeof value !== 'number' || isNaN(value))) {
            value = DEFAULT_VALUES[key as keyof typeof DEFAULT_VALUES];
        }

        onChange({
            ...legend,
            [key]: value
        });
    };

    const handlePositionChange = (key: string, value: any) => {
        onChange({
            ...legend,
            position: {
                ...legend.position,
                [key]: value
            }
        });
    };

    const handleTextStyleChange = (key: string, value: any) => {
        onChange({
            ...legend,
            textStyle: {
                ...legend.textStyle,
                [key]: value
            }
        });
    };

    const handlePageTextStyleChange = (key: string, value: any) => {
        onChange({
            ...legend,
            pageTextStyle: {
                ...legend.pageTextStyle,
                [key]: value
            }
        });
    };

    // 创建通用的InputNumber组件
    const renderNumberInput = (
        label: string,
        fieldKey: keyof LegendConfigType,
        defaultValue: number,
        min = 0,
        max?: number,
        disabled = false,
        addonText = 'px'
    ) => (
        <Form.Item style={{ marginBottom: 8 }}>
            <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                {label}
            </Typography.Text>
            <InputNumber
                size="small"
                value={legend[fieldKey] as number || defaultValue}
                onChange={(value) => handleChange(fieldKey, handleNumberValue(value, defaultValue))}
                min={min}
                max={max}
                disabled={disabled}
                addonAfter={addonText}
                style={{ width: '100%' }}
            />
        </Form.Item>
    );

    // 预设面板内容
    const presetsContent = (
        <div style={{ width: 300, maxHeight: 400, overflow: 'auto' }}>
            <Typography.Title level={5}>应用预设样式</Typography.Title>
            <Row gutter={[8, 8]}>
                {allPresets.map((preset) => (
                    <Col span={12} key={preset.name}>
                        <div
                            style={{
                                border: '1px solid #d9d9d9',
                                borderRadius: 4,
                                padding: 8,
                                cursor: 'pointer',
                                backgroundColor: lastAppliedPreset === preset.name ? '#e6f7ff' : 'transparent',
                                position: 'relative'
                            }}
                            onClick={() => {
                                applyPreset(preset.config);
                                setLastAppliedPreset(preset.name);
                                message.success(`已应用"${preset.name}"预设`);
                            }}
                        >
                            <Typography.Text strong ellipsis style={{ display: 'block' }}>
                                {preset.name}
                            </Typography.Text>
                            {/* 预设示例 - 模拟预览 */}
                            <div style={{
                                height: 40,
                                backgroundColor: preset.config.backgroundColor || 'transparent',
                                borderRadius: typeof preset.config.borderRadius === 'number' ? `${preset.config.borderRadius}px` : '0px',
                                border: preset.config.borderWidth ? `${preset.config.borderWidth}px solid ${preset.config.borderColor || '#000'}` : 'none',
                                padding: '4px 8px',
                                display: 'flex',
                                flexDirection: preset.config.orient === 'vertical' ? 'column' : 'row',
                                justifyContent: 'center',
                                alignItems: 'center',
                                gap: preset.config.itemGap || 10,
                                marginTop: 4
                            }}>
                                {['系列1', '系列2'].map((item, index) => (
                                    <div key={index} style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                                        <div style={{
                                            width: Math.min(12, (preset.config.itemWidth || 25) / 2),
                                            height: Math.min(6, (preset.config.itemHeight || 14) / 2),
                                            backgroundColor: ['#5470c6', '#91cc75'][index % 2]
                                        }} />
                                        <span style={{
                                            color: preset.config.textStyle?.color || '#333',
                                            fontSize: Math.min(10, (preset.config.textStyle?.fontSize || 12) / 1.2)
                                        }}>{item}</span>
                                    </div>
                                ))}
                            </div>

                            {/* 删除按钮 - 仅显示在自定义预设上 */}
                            {!preset.isDefault && (
                                <Button
                                    type="text"
                                    size="small"
                                    icon={<DeleteOutlined />}
                                    style={{ position: 'absolute', top: 2, right: 2 }}
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        deletePreset(preset.name);
                                    }}
                                />
                            )}
                        </div>
                    </Col>
                ))}
            </Row>
            <Divider style={{ margin: '12px 0' }} />
            <Button
                type="primary"
                icon={<SaveOutlined />}
                block
                onClick={() => setShowPresetModal(true)}
            >
                保存当前样式为预设
            </Button>
        </div>
    );

    // 基本设置面板内容
    const basicSettingsPanel = (
        <>
            <Form.Item
                label="显示图例"
                valuePropName="checked"
                style={{ marginBottom: 8 }}
            >
                <Switch
                    checked={legend.show !== false}
                    onChange={(checked) => handleChange('show', checked)}
                    size="small"
                />
            </Form.Item>

            {legend.show !== false && (
                <>
                    <Row gutter={16}>
                        <Col span={12}>
                            <Form.Item style={{ marginBottom: 8 }}>
                                <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                                    水平位置
                                </Typography.Text>
                                <Select
                                    size="small"
                                    value={legend.position?.left || 'right'}
                                    onChange={(value) => handlePositionChange('left', value)}
                                    style={{ width: '100%' }}
                                >
                                    <Select.Option value="left">左侧</Select.Option>
                                    <Select.Option value="center">居中</Select.Option>
                                    <Select.Option value="right">右侧</Select.Option>
                                </Select>
                            </Form.Item>
                        </Col>
                        <Col span={12}>
                            <Form.Item style={{ marginBottom: 8 }}>
                                <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                                    垂直位置
                                </Typography.Text>
                                <Select
                                    size="small"
                                    value={legend.position?.top || 'top'}
                                    onChange={(value) => handlePositionChange('top', value)}
                                    style={{ width: '100%' }}
                                >
                                    <Select.Option value="top">顶部</Select.Option>
                                    <Select.Option value="middle">中部</Select.Option>
                                    <Select.Option value="bottom">底部</Select.Option>
                                </Select>
                            </Form.Item>
                        </Col>
                    </Row>

                    <Form.Item style={{ marginBottom: 8 }}>
                        <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                            摆放方向
                        </Typography.Text>
                        <Select
                            size="small"
                            value={legend.orient || 'horizontal'}
                            onChange={(value) => handleChange('orient', value)}
                            style={{ width: '100%' }}
                        >
                            <Select.Option value="horizontal">水平</Select.Option>
                            <Select.Option value="vertical">垂直</Select.Option>
                        </Select>
                    </Form.Item>

                    <Form.Item style={{ marginBottom: 8 }}>
                        <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                            选择模式
                        </Typography.Text>
                        <Select
                            size="small"
                            value={legend.selectedMode}
                            onChange={(value) => handleChange('selectedMode', value)}
                            style={{ width: '100%' }}
                        >
                            <Select.Option value={true}>多选</Select.Option>
                            <Select.Option value="single">单选</Select.Option>
                            <Select.Option value={false}>禁用选择</Select.Option>
                        </Select>
                    </Form.Item>
                </>
            )}
        </>
    );

    // 图标设置面板内容
    const iconSettingsPanel = (
        <>
            <Form.Item style={{ marginBottom: 8 }}>
                <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                    图标形状
                </Typography.Text>
                <Select
                    size="small"
                    value={legend.icon || 'rect'}
                    onChange={(value) => handleChange('icon', value)}
                    style={{ width: '100%' }}
                >
                    <Select.Option value="circle">圆形</Select.Option>
                    <Select.Option value="rect">矩形</Select.Option>
                    <Select.Option value="roundRect">圆角矩形</Select.Option>
                    <Select.Option value="triangle">三角形</Select.Option>
                    <Select.Option value="diamond">菱形</Select.Option>
                    <Select.Option value="pin">标注</Select.Option>
                    <Select.Option value="arrow">箭头</Select.Option>
                </Select>
            </Form.Item>

            <Row gutter={16}>
                <Col span={12}>
                    {renderNumberInput('图标宽度', 'itemWidth', DEFAULT_VALUES.itemWidth)}
                </Col>
                <Col span={12}>
                    {renderNumberInput('图标高度', 'itemHeight', DEFAULT_VALUES.itemHeight)}
                </Col>
            </Row>

            {renderNumberInput('图例项间距', 'itemGap', DEFAULT_VALUES.itemGap)}

            <Form.Item style={{ marginBottom: 8 }}>
                <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                    未选中颜色
                </Typography.Text>
                <ColorPicker
                    value={legend.inactiveColor || '#ccc'}
                    onChange={(color) => handleChange('inactiveColor', color)}
                    showAlpha={true}
                />
            </Form.Item>
        </>
    );

    // 文字样式面板内容
    const textStylePanel = (
        <>
            <Row gutter={16}>
                <Col span={12}>
                    <Form.Item style={{ marginBottom: 8 }}>
                        <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                            文字颜色
                        </Typography.Text>
                        <ColorPicker
                            value={legend.textStyle?.color || '#333333'}
                            onChange={(color) => handleTextStyleChange('color', color)}
                            showAlpha={true}
                        />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item style={{ marginBottom: 8 }}>
                        <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                            字号
                        </Typography.Text>
                        <InputNumber
                            size="small"
                            value={legend.textStyle?.fontSize || 12}
                            onChange={(value) => handleTextStyleChange('fontSize', value)}
                            min={0}
                            addonAfter="px"
                            style={{ width: '100%' }}
                        />
                    </Form.Item>
                </Col>
            </Row>

            <Row gutter={16}>
                <Col span={12}>
                    <Form.Item style={{ marginBottom: 8 }}>
                        <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                            字重
                        </Typography.Text>
                        <Select
                            size="small"
                            value={legend.textStyle?.fontWeight || 'normal'}
                            onChange={(value) => handleTextStyleChange('fontWeight', value)}
                            style={{ width: '100%' }}
                        >
                            <Select.Option value="normal">普通</Select.Option>
                            <Select.Option value="bold">粗体</Select.Option>
                            <Select.Option value="bolder">特粗</Select.Option>
                            <Select.Option value="lighter">细体</Select.Option>
                        </Select>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item style={{ marginBottom: 8 }}>
                        <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                            字体样式
                        </Typography.Text>
                        <Select
                            size="small"
                            value={legend.textStyle?.fontStyle || 'normal'}
                            onChange={(value) => handleTextStyleChange('fontStyle', value)}
                            style={{ width: '100%' }}
                        >
                            <Select.Option value="normal">普通</Select.Option>
                            <Select.Option value="italic">斜体</Select.Option>
                        </Select>
                    </Form.Item>
                </Col>
            </Row>

            <Form.Item style={{ marginBottom: 8 }}>
                <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                    字体
                </Typography.Text>
                <Input
                    size="small"
                    value={legend.textStyle?.fontFamily || ''}
                    onChange={(e) => handleTextStyleChange('fontFamily', e.target.value)}
                    placeholder="sans-serif"
                />
            </Form.Item>
        </>
    );

    // 背景样式面板内容
    const backgroundStylePanel = (
        <>
            <Row gutter={16}>
                <Col span={12}>
                    <Form.Item style={{ marginBottom: 8 }}>
                        <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                            背景颜色
                        </Typography.Text>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            <Switch
                                size="small"
                                checked={legend.backgroundColor !== 'transparent' && !!legend.backgroundColor}
                                onChange={(checked) => {
                                    handleChange('backgroundColor', checked ? '#ffffff' : 'transparent');
                                }}
                                style={{ marginRight: 8 }}
                            />
                            <ColorPicker
                                value={legend.backgroundColor === 'transparent' ? '#ffffff' : (legend.backgroundColor || '#ffffff')}
                                onChange={(color) => handleChange('backgroundColor', color)}
                                showAlpha={true}
                                disabled={legend.backgroundColor === 'transparent'}
                            />
                        </div>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item style={{ marginBottom: 8 }}>
                        <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                            边框颜色
                        </Typography.Text>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            <Switch
                                size="small"
                                checked={legend.borderColor !== 'transparent' && !!legend.borderColor}
                                onChange={(checked) => {
                                    handleChange('borderColor', checked ? '#cccccc' : 'transparent');
                                }}
                                style={{ marginRight: 8 }}
                            />
                            <ColorPicker
                                value={legend.borderColor === 'transparent' ? '#cccccc' : (legend.borderColor || '#cccccc')}
                                onChange={(color) => handleChange('borderColor', color)}
                                showAlpha={true}
                                disabled={legend.borderColor === 'transparent'}
                            />
                        </div>
                    </Form.Item>
                </Col>
            </Row>

            <Row gutter={16}>
                <Col span={12}>
                    {renderNumberInput('边框宽度', 'borderWidth', DEFAULT_VALUES.borderWidth)}
                </Col>
                <Col span={12}>
                    {renderNumberInput('圆角半径', 'borderRadius', DEFAULT_VALUES.borderRadius)}
                </Col>
            </Row>

            {renderNumberInput('内边距', 'padding', DEFAULT_VALUES.padding)}

            <Divider orientation="left" style={{ margin: '12px 0', fontSize: 12 }}>阴影设置</Divider>

            <Row gutter={16}>
                <Col span={12}>
                    <Form.Item style={{ marginBottom: 8 }}>
                        <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                            阴影颜色
                        </Typography.Text>
                        <div style={{ display: 'flex', alignItems: 'center' }}>
                            <Switch
                                size="small"
                                checked={!!legend.shadowColor}
                                onChange={(checked) => {
                                    handleChange('shadowColor', checked ? 'rgba(0, 0, 0, 0.2)' : undefined);
                                }}
                                style={{ marginRight: 8 }}
                            />
                            <ColorPicker
                                value={legend.shadowColor || 'rgba(0, 0, 0, 0.2)'}
                                onChange={(color) => handleChange('shadowColor', color)}
                                showAlpha={true}
                                disabled={!legend.shadowColor}
                            />
                        </div>
                    </Form.Item>
                </Col>
                <Col span={12}>
                    {renderNumberInput(
                        '阴影模糊大小',
                        'shadowBlur',
                        DEFAULT_VALUES.shadowBlur,
                        0,
                        100,
                        !legend.shadowColor
                    )}
                </Col>
            </Row>

            <Row gutter={16}>
                <Col span={12}>
                    {renderNumberInput(
                        '阴影水平偏移',
                        'shadowOffsetX',
                        DEFAULT_VALUES.shadowOffsetX,
                        undefined,
                        undefined,
                        !legend.shadowColor
                    )}
                </Col>
                <Col span={12}>
                    {renderNumberInput(
                        '阴影垂直偏移',
                        'shadowOffsetY',
                        DEFAULT_VALUES.shadowOffsetY,
                        undefined,
                        undefined,
                        !legend.shadowColor
                    )}
                </Col>
            </Row>
        </>
    );

    // 分页设置面板内容
    const paginationPanel = (
        <>
            <Form.Item style={{ marginBottom: 8 }}>
                <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                    分页按钮位置
                </Typography.Text>
                <Select
                    size="small"
                    value={legend.pageButtonPosition || 'end'}
                    onChange={(value) => handleChange('pageButtonPosition', value)}
                    style={{ width: '100%' }}
                >
                    <Select.Option value="start">开始</Select.Option>
                    <Select.Option value="end">结束</Select.Option>
                </Select>
            </Form.Item>

            <Row gutter={16}>
                <Col span={12}>
                    <Form.Item style={{ marginBottom: 8 }}>
                        <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                            按钮颜色
                        </Typography.Text>
                        <ColorPicker
                            value={legend.pageIconColor || '#2f4554'}
                            onChange={(color) => handleChange('pageIconColor', color)}
                            showAlpha={true}
                        />
                    </Form.Item>
                </Col>
                <Col span={12}>
                    <Form.Item style={{ marginBottom: 8 }}>
                        <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                            未激活颜色
                        </Typography.Text>
                        <ColorPicker
                            value={legend.pageIconInactiveColor || '#aaa'}
                            onChange={(color) => handleChange('pageIconInactiveColor', color)}
                            showAlpha={true}
                        />
                    </Form.Item>
                </Col>
            </Row>

            {renderNumberInput('按钮大小', 'pageIconSize', DEFAULT_VALUES.pageIconSize)}

            <Form.Item style={{ marginBottom: 8 }}>
                <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                    分页文本颜色
                </Typography.Text>
                <ColorPicker
                    value={legend.pageTextStyle?.color || '#333'}
                    onChange={(color) => handlePageTextStyleChange('color', color)}
                    showAlpha={true}
                />
            </Form.Item>
        </>
    );

    // 动画设置面板内容
    const animationPanel = (
        <>
            <Form.Item style={{ marginBottom: 8 }}>
                <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                    启用动画
                </Typography.Text>
                <Switch
                    checked={legend.animation !== false}
                    onChange={(checked) => handleChange('animation', checked)}
                    size="small"
                />
            </Form.Item>

            {renderNumberInput(
                '动画时长',
                'animationDurationUpdate',
                DEFAULT_VALUES.animationDurationUpdate,
                0,
                undefined,
                legend.animation === false,
                'ms'
            )}
        </>
    );

    // 高级设置面板内容
    const advancedPanel = (
        <>
            <div style={{ marginBottom: 12 }}>
                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                    <Tooltip title="查看ECharts官方文档中关于图例的详细说明">
                        <Button
                            type="link"
                            size="small"
                            icon={<LinkOutlined />}
                            onClick={() => window.open('./docs/option-legend.html', '_blank')}
                        >
                            查看文档
                        </Button>
                    </Tooltip>
                </div>
            </div>

            <Form.Item style={{ marginBottom: 8 }}>
                <Typography.Text type="secondary" style={{ marginBottom: 4, display: 'block', fontSize: 12 }}>
                    格式化器
                </Typography.Text>
                <Input
                    size="small"
                    value={typeof legend.formatter === 'string' ? legend.formatter : ''}
                    onChange={(e) => handleChange('formatter', e.target.value)}
                    placeholder="{name}"
                />
                <Typography.Text type="secondary" style={{ marginTop: 4, display: 'block', fontSize: 12 }}>
                    模板变量: {'{name}'} 表示图例项名称
                </Typography.Text>
            </Form.Item>
        </>
    );

    // 定义标签页内容
    const tabItems: TabsProps['items'] = [
        {
            key: '1',
            label: '基本',
            children: basicSettingsPanel
        },
        {
            key: '2',
            label: '图标样式',
            children: iconSettingsPanel
        },
        {
            key: '3',
            label: '文字样式',
            children: textStylePanel
        },
        {
            key: '4',
            label: '背景样式',
            children: backgroundStylePanel
        },
        {
            key: '5',
            label: '分页设置',
            children: paginationPanel
        },
        {
            key: '6',
            label: '动画',
            children: animationPanel
        },
        {
            key: '7',
            label: '高级',
            children: advancedPanel
        }
    ];

    return (
        <div style={{ padding: 12, background: '#fff', borderRadius: 4 }}>
            {/* 图例预览（简化版） */}
            <div
                style={{
                    marginBottom: 16,
                    padding: 16,
                    border: '1px dashed #d9d9d9',
                    borderRadius: 4,
                    backgroundColor: '#fafafa'
                }}
            >
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                    {/* 预览区域 */}
                    <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 16 }}>
                        {legend.show !== false && (
                            <div
                                style={{
                                    display: 'inline-flex',
                                    flexDirection: legend.orient === 'vertical' ? 'column' : 'row',
                                    alignItems: 'flex-start',
                                    backgroundColor: legend.backgroundColor || 'transparent',
                                    borderColor: legend.borderColor || 'transparent',
                                    borderWidth: legend.borderWidth ? `${legend.borderWidth}px` : '0',
                                    borderStyle: 'solid',
                                    borderRadius: typeof legend.borderRadius === 'number' ? `${legend.borderRadius}px` : '0',
                                    padding: '5px 10px',
                                    boxShadow: legend.shadowColor ?
                                        `${legend.shadowOffsetX || 0}px ${legend.shadowOffsetY || 0}px ${legend.shadowBlur || 0}px ${legend.shadowColor}` : 'none'
                                }}
                            >
                                {['系列1', '系列2', '系列3'].map((item, index) => (
                                    <div
                                        key={index}
                                        style={{
                                            display: 'flex',
                                            alignItems: 'center',
                                            marginRight: legend.orient === 'horizontal' ? (legend.itemGap || 10) : 0,
                                            marginBottom: legend.orient === 'vertical' ? (legend.itemGap || 10) : 0,
                                        }}
                                    >
                                        <span style={{
                                            display: 'inline-block',
                                            width: legend.itemWidth || 25,
                                            height: legend.itemHeight || 14,
                                            marginRight: '5px',
                                            backgroundColor: ['#5470c6', '#91cc75', '#fac858'][index % 3]
                                        }}></span>
                                        <span style={{
                                            color: legend.textStyle?.color || '#333',
                                            fontSize: `${legend.textStyle?.fontSize || 12}px`,
                                            fontWeight: legend.textStyle?.fontWeight || 'normal',
                                            fontStyle: legend.textStyle?.fontStyle || 'normal',
                                            fontFamily: legend.textStyle?.fontFamily || 'sans-serif',
                                        }}>
                                            {item}
                                        </span>
                                    </div>
                                ))}
                            </div>
                        )}
                    </div>

                    {/* 控制栏 */}
                    <Divider style={{ margin: '0 0 12px' }} />

                    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                        <Form.Item
                            label="显示图例"
                            valuePropName="checked"
                            style={{ marginBottom: 0 }}
                        >
                            <Switch
                                checked={legend.show !== false}
                                onChange={(checked) => handleChange('show', checked)}
                                size="small"
                            />
                        </Form.Item>

                        <Space>
                            <Tooltip title="导出当前配置">
                                <Button
                                    size="small"
                                    icon={<ExportOutlined />}
                                    onClick={() => {
                                        try {
                                            const configJson = JSON.stringify(legend, null, 2);
                                            navigator.clipboard.writeText(configJson);
                                            message.success('图例配置已复制到剪贴板');
                                        } catch (e) {
                                            console.error('导出配置失败', e);
                                            message.error('导出配置失败');
                                        }
                                    }}
                                >
                                    导出
                                </Button>
                            </Tooltip>

                            <Popover
                                content={presetsContent}
                                title={null}
                                trigger="click"
                                placement="bottomRight"
                            >
                                <Button
                                    size="small"
                                    type="primary"
                                    icon={<ImportOutlined />}
                                >
                                    应用预设
                                </Button>
                            </Popover>
                        </Space>
                    </div>
                </div>
            </div>

            <Tabs
                activeKey={activeTab}
                onChange={setActiveTab}
                size="small"
                items={tabItems}
            />

            {/* 保存预设模态对话框 */}
            <Modal
                title="保存为预设样式"
                open={showPresetModal}
                onOk={handleSavePreset}
                onCancel={() => setShowPresetModal(false)}
                okText="保存"
                cancelText="取消"
            >
                <div style={{ marginBottom: 16 }}>
                    <Typography.Paragraph>
                        将当前图例配置保存为预设，方便下次快速应用。
                    </Typography.Paragraph>
                </div>
                <Form.Item label="预设名称" required>
                    <Input
                        placeholder="请输入预设名称"
                        value={presetName}
                        onChange={(e) => setPresetName(e.target.value)}
                        autoFocus
                    />
                </Form.Item>
            </Modal>
        </div>
    );
};

export default LegendConfig; 